<template>
    <div class="home">
        <el-row>
            <el-col :span="1">
                <div class="nav">
                    <div class="user_pic" plain @click="dialogFormVisible = true"><img :src="userStore.avatar ?? ''"
                            alt="">
                    </div>
                    <div class="news" @click="gotonews">
                        <ChatDotSquare :class="newscheck" />
                    </div>
                    <div class="friend" @click="gotofriends">
                        <User :class="friendcheck" />
                    </div>
                </div>
            </el-col>
            <el-col :span="23">
                <div class="main">
                    <router-view></router-view>
                </div>
            </el-col>
        </el-row>

    </div>
    <el-dialog v-model="dialogFormVisible" title="" width="450" class="info">
        <el-form :inline="true">
            <el-form-item>
                <div class="pic"><img :src="userStore.avatar ?? ''" alt=""> </div>

            </el-form-item>
            <el-form-item>
                <div class="right">
                    <div class="name">{{ userStore.username }}</div>
                    <div class="remark">用户ID：{{ userStore.userId }}</div>
                    <div class="region">地区：广东 广州</div>
                </div>
            </el-form-item>

        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary">发信息</el-button>
                <el-button type="primary" @click="logout">退出登录</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { User, ChatDotSquare } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
//引入用户相关的仓库,获取当前用户的头像、昵称
import useUserStore from '@/store/modules/user';
import io from 'socket.io-client';
import useUserChatStore from '@/store/modules/userchat';
//获取存储用户信息的仓库对象
let userStore = useUserStore();
let userChatStore = useUserChatStore();
let newscheck = ref('check');
let friendcheck = ref('uncheck');
let socket: any = null;
const router = useRouter();
const route = useRoute(); // 获取当前路由信息
const dialogFormVisible = ref(false)
onMounted(() => {
    checked()
    socket = io('http://localhost:8080'); // 连接到你的 Socket.IO 服务器
    socket.on('connect', () => {
        console.log('Connected to Socket.IO server');
    });
    // 动态遍历 userStore.friendsList，加入每个房间
    userStore.friendsList.forEach((friend: any) => {
        socket.emit('joinRoom', { userId: userStore.userId, roomName: friend.roomName });
        console.log(`Joined room: ${friend.roomName}`);
    });
    // 监听接收到的消息
    socket.on('receiveMsg', async (msg: any) => {
        console.log(msg.roomName);
        // 如果receiverId==userStore.userId,
        if (msg.message.receiverId == userStore.userId) {
            //    如果房间是打开的就已读消息，如果没有打开就获取未读信息数量，并更新最后一条未读信息内容
        //    await  userChatStore.friendsChat(userStore.userId as string)
            // 获取路由
            const activeTab = route.meta.activeTab;
            // 获取打开界面的房间号
            const roomName=route.params.roomName;
            console.log(roomName);
            
            console.log(activeTab);
            // 没有进入判断？？？
            if (activeTab === 'chat'&&roomName===msg.roomName) {
                
                // 获取聊天记录，并已读,会把别的用户的给已读了，
                // 解决方法：获取房间号，双重验证，保证是将房间打开的，用户为接收者的信息已读，修改聊天记录模型，添加房间号，已验证消息是哪个房间的，要修改多个路由
                await userChatStore.getChatRecords(userStore.userId as string,roomName as string)
                // 更新最后一条信息
                await  userChatStore.updatefriendChat(userStore.userId as string,roomName as string)
                console.log('已读');
            }
            else {
                console.log('接收消息，未读');
                
                // 获取聊天记录，并已读
                await  userChatStore.updatefriendChat(userStore.userId as string,msg.roomName)
            }
        }

    });
})
onBeforeUnmount(() => {
    if (socket) {
        socket.disconnect(); // 在组件销毁时断开连接
        console.log('Socket.IO connection disconnected');
    }
});
// 导航栏选中
const checked = () => {
    const activeTab = route.meta.activeTab;
    // 处理 activeTab 为 'friends' 或 'frien' 的情况
    if (activeTab === 'friends' || activeTab === 'frien' || activeTab === 'newfriend') {
        friendcheck.value = 'check';
        newscheck.value = 'uncheck';
    } else {
        // 处理 activeTab 为 'news' 或 'chat' 的情况
        newscheck.value = 'check';
        friendcheck.value = 'uncheck';
    }
}

const gotonews = () => {
    if (newscheck.value !== 'check') {
        router.push('/news');
        newscheck.value = 'check';
        friendcheck.value = 'uncheck';
    }

}
const gotofriends = () => {
    if (friendcheck.value !== "check") {
        router.push('/friends');
        friendcheck.value = 'check';
        newscheck.value = 'uncheck';
    }

}
const logout = async () => {
    await userStore.userLogout();
    router.push({ path: '/login', query: { redirect: route.path } })
}
// 路由变化时检查选中的导航
watch(route, () => {
    checked();
}, { immediate: true }); // { immediate: true } 确保在组件挂载时即执行一次
</script>

<style scoped lang="scss">
.home {
    width: 100%;
    height: 100vh;
    background-color: #f1f1f1;

    .nav {
        position: fixed;
        top: 0;
        left: 0;
        padding: 40px 5px;
        color: white;
        width: 4.17%;
        height: 100vh;
        background: linear-gradient(to right, #c5d4ef, #9bb7f1);
        z-index: 11;
        /* 确保导航栏位于页面最上层 */
        display: flex;
        flex-direction: column;
        align-items: center;

        .user_pic {
            width: 50px;
            height: 50px;
            background-color: #fff;
            margin-bottom: 20px;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }

        .news,
        .friend {
            z-index: 11;
            width: 50px;
            height: 50px;
            padding: 10px;
        }

        .check {
            color: #5b8ef5;
        }

        .uncheck {
            color: white
        }

    }

    .main {
        width: 100%;
    }




}

.info {
    width: 100%;
    margin: auto;

    .pic {

        img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 5px;
        }
    }

    .right {}
}
</style>